<?php
namespace App\Noxinfluencer\Controllers;

require_once '../../../vendor/autoload.php';

use Medoo\Medoo;
use phpspider\core\db;
use phpspider\core\phpspider;
use phpspider\core\requests;
use phpspider\core\selector;

$db = new Medoo([
    'database_type' => 'mysql',
    'database_name' => 'youtube',
    'server' => '127.0.0.1',
    'username' => 'root',
    'password' => 'wewrjjdsl@oo888rmds'
]);


$pageSize = 5000;

/*$channel_id = 'UC-F6LZSWz34xKknY8NNCzgQ';

$userinfo = $db->get('user_nox',['id'],['channel_id'=>$channel_id]);*/

while(true) {

    $users = $db->select('user_nox', [
        "[>]user_video" => ["id" => "user_id"],
    ], [
        'user_nox.id',
        'user_nox.channel_id',
        'user_video.user_id',
    ], [
        "user_video.user_id" => null,
        "ORDER" => ["user_nox.id" => "ASC"],
        "LIMIT" => 10000
    ]);

    foreach ($users as $key => $value) {

        $url = "https://cn.noxinfluencer.com/api/video/list?pageSize=$pageSize&channelId={$value['channel_id']}&offset=0&sortField=pub_date&isPredicted=0";
        $data = requests::get($url);

        $cotnet = json_decode($data, true);
        $html = $cotnet['retData']['dom'];

// 选择器规则
        $video_id = selector::select($html, "//div[@class='video-wrapper']/@data-video-id");

        $img = selector::select($html, "//img[@class='thumb']/@src");

        $title = selector::select($html, "//a[@class='underline']");

        $video_look_num_data = selector::select($html, "//div[@class='detail']//div[@class='subtitle']");

        $save_data = [];

        if(is_array($video_id)) {
            for ($i = 0; $i < count($video_id); $i++) {
                $video_look_num = explode(' 观看量 · ', $video_look_num_data[$i]);

                $save_data[$i] = array(
                    'user_id' => $value['id'],
                    'video_youtube_id' => $video_id[$i],
                    'video_pic' => $img[$i],
                    'video_name' => $title[$i],
                    'video_look_num' => str_replace(['万', '亿', '.'], ['0000', '00000000', ''], $video_look_num[0]),
                    'video_upload_time' => str_replace([' 视频发布时间'], [''], $video_look_num[1]),
                    'create_time' => date('Y-m-d H:i:s', time()),
                    'update_time' => date('Y-m-d H:i:s', time()),
                );
            }


            $db->insert('user_video', $save_data);
        }

        echo $value['id']."-";
    }

    echo "\n一个周期结束\n";

    sleep(1);
}





